package model;

import java.awt.Point;

public class Rules {

	/**
	 * Guarda o vencedor.
	 */
	public static PieceType winner;

	/**
	 * Verifica se o jogo já acabou.
	 */
	public static boolean gameOver(Board board) {
		PieceType[][] mat = board.getPieces();
		PieceType last1 = null, last2 = null, last3 = null, actual = null;
		
		/* Testa se houve vitória nas linhas. */
		for (int i = 0; i < mat.length; i++) {
			last3 = board.getPieces()[i][0];
			last2 = board.getPieces()[i][1];
			last1 = board.getPieces()[i][2];
			for (int j = 3; j < mat[i].length; j++) {
				actual = mat[i][j];
				if (actual != PieceType.NONE && last3.equals(last2) && last2.equals(last1) && last1.equals(actual)) {
					winner = actual;
					return true;
				}
				last3 = last2;
				last2 = last1;
				last1 = actual;
			}
		}
		
		/* Testa se houve vitória nas colunas. */
		for (int j = 0; j < mat[0].length; j++) {
			last3 = board.getPieces()[0][j];
			last2 = board.getPieces()[1][j];
			last1 = board.getPieces()[2][j];
			for (int i = 3; i < mat.length; i++) {
				actual = mat[i][j];
				if (actual != PieceType.NONE && last3.equals(last2) && last2.equals(last1) && last1.equals(actual)) {
					winner = actual;
					return true;
				}
				last3 = last2;
				last2 = last1;
				last1 = actual;
			}
		}
		
		/* Testa se houve vitória na diagonal 1. */
		for (int i = 0; i < mat.length - 3; i++) {
			for (int j = 0; j < mat[i].length - 3; j++) {
				actual = mat[i][j];
				last1 = mat[i+1][j+1];
				last2 = mat[i+2][j+2];
				last3 = mat[i+3][j+3];
				if (actual != PieceType.NONE && last3.equals(last2) && last2.equals(last1) && last1.equals(actual)) {
					winner = actual;
					return true;
				}
			}
		}
		
		/* Testa se houve vitória na diagonal 2. */
		for (int i = 0; i < mat.length - 3; i++) {
			for (int j = 3; j < mat[i].length; j++) {
				actual = mat[i][j];
				last1 = mat[i+1][j-1];
				last2 = mat[i+2][j-2];
				last3 = mat[i+3][j-3];
				if (actual != PieceType.NONE && last3.equals(last2) && last2.equals(last1) && last1.equals(actual)) {
					winner = actual;
					return true;
				}
			}
		}
		
		return false;
	}

	/**
	 * Verifica se uma jogada é válida.
	 */
	public static boolean isValid(Point pos, Board board) {
		if (pos.x < board.getRows() - 1 && board.getPieces()[pos.x + 1][pos.y] == PieceType.NONE) return false;
		if (board.getPieces()[pos.x][pos.y] != PieceType.NONE) return false;
		return true;
	}

}
